<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<input 
				type="text" 
				placeholder="搜索宠物名称" 
				v-model="searchKeyword"
				@input="searchPets"
				class="search-input"
			/>
		</view>
		
		<!-- 宠物列表 -->
		<view class="pet-list" v-if="pets.length > 0">
			<view 
				class="pet-item" 
				v-for="pet in pets" 
				:key="pet.id"
				@click="viewPetDetail(pet.id)"
			>
				<view class="pet-avatar">
					<image 
						:src="pet.photo || '/static/img/default-pet.png'" 
						mode="aspectFill"
						class="avatar-image"
					></image>
				</view>
				<view class="pet-info">
					<view class="pet-name">{{pet.name}}</view>
					<view class="pet-details">
						<text class="breed">{{pet.breed}}</text>
						<text class="gender">{{pet.gender}}</text>
					</view>
					<view class="pet-birthday" v-if="pet.birthday">
						生日: {{formatDate(pet.birthday)}}
					</view>
				</view>
				<view class="pet-actions">
					<view 
						class="settings-icon" 
						@click.stop="showSettings(pet.id)"
					>
						<text class="icon">⚙️</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<image src="/static/img/empty-pets.png" class="empty-image"></image>
			<text class="empty-text">还没有添加宠物</text>
			<button class="add-btn" @click="addPet">添加宠物</button>
		</view>
		
		<!-- 悬浮添加按钮 -->
		<view class="fab" @click="addPet">
			<text class="fab-icon">+</text>
		</view>
	</view>
</template>

<script>
import userStore from '@/store/user'
import { getPetList, deletePet } from '@/api/pet.js'
import { getHealthList, deleteHealthRecord } from '@/api/health.js'

export default {
	data() {
		return {
			pets: [],
			searchKeyword: '',
			loading: false
		}
	},
	onLoad() {
		this.loadPets()
	},
	onShow() {
		this.loadPets()
	},
	methods: {
		async loadPets() {
			// 检查登录状态
			if (!userStore.getters.isLoggedIn) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				uni.navigateTo({
					url: '/pages/login'
				})
				return
			}
			
			const userId = userStore.state.userInfo.userId
			if (!userId) {
				uni.showToast({
					title: '用户信息获取失败',
					icon: 'none'
				})
				return
			}
			
			this.loading = true
			try {
				const response = await getPetList(userId)
				
				
				if (response && response.code === 200) {
					const petData = response.rows || response.data || []
					this.pets = Array.isArray(petData) ? petData : []
					
				} else {
					
					uni.showToast({
						title: response?.msg || '加载失败',
						icon: 'none'
					})
					this.pets = []
				}
			} catch (error) {
				
				this.pets = []
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		
		searchPets() {
			if (!this.searchKeyword.trim()) {
				this.loadPets()
				return
			}
			
			// 本地搜索
			this.pets = this.pets.filter(pet => 
				pet.name.toLowerCase().includes(this.searchKeyword.toLowerCase())
			)
		},
		
		viewPetDetail(petId) {
			uni.navigateTo({
				url: `/pages/pet/detail?id=${petId}`
			})
		},
		
		editPet(petId) {
			uni.navigateTo({
				url: `/pages/pet/edit?id=${petId}`
			})
		},
		
		addPet() {
			uni.navigateTo({
				url: '/pages/pet/add'
			})
		},
		
		showSettings(petId) {
			uni.showActionSheet({
				itemList: ['编辑', '删除'],
				success: (res) => {
					if (res.tapIndex === 0) {
						// 编辑
						this.editPet(petId)
					} else if (res.tapIndex === 1) {
						// 删除
						this.deletePet(petId)
					}
				}
			})
		},
		
		async deletePet(petId) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个宠物吗？删除后将同时删除所有相关健康记录，且无法恢复。',
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({ title: '删除中...' })
							
							// 1. 先获取该宠物的所有健康记录
							const healthResponse = await getHealthList({ petId: petId })
							let healthRecords = []
							if (healthResponse && healthResponse.code === 200) {
								healthRecords = healthResponse.data || healthResponse.rows || []
							}
							
							// 2. 删除所有健康记录
							if (healthRecords.length > 0) {
								const deletePromises = healthRecords.map(record => 
									deleteHealthRecord(record.id).catch(err => {
										
										// 单个健康记录删除失败不影响整体流程
										return null
									})
								)
								await Promise.all(deletePromises)
							}
							
							// 3. 删除宠物
							const response = await deletePet(petId)
							
							
							if (response && response.code === 200) {
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})
								this.loadPets()
							} else {
								
								uni.showToast({
									title: response?.msg || '删除失败',
									icon: 'none'
								})
							}
						} catch (error) {
							
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							})
						} finally {
							uni.hideLoading()
						}
					}
				}
			})
		},
		
		formatDate(dateString) {
			const date = new Date(dateString)
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
		}
	}
}
</script>

<style scoped>
.container {
	padding: 20rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

.search-bar {
	margin-bottom: 20rpx;
}

.search-input {
	background: white;
	padding: 20rpx;
	border-radius: 10rpx;
	font-size: 28rpx;
}

.pet-list {
	margin-bottom: 120rpx;
}

.pet-item {
	background: white;
	border-radius: 15rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.pet-avatar {
	margin-right: 30rpx;
}

.avatar-image {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
}

.pet-info {
	flex: 1;
}

.pet-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 10rpx;
}

.pet-details {
	margin-bottom: 10rpx;
}

.breed {
	font-size: 26rpx;
	color: #666;
	margin-right: 20rpx;
}

.gender {
	font-size: 26rpx;
	color: #007AFF;
}

.pet-birthday {
	font-size: 24rpx;
	color: #999;
}

.pet-actions {
	display: flex;
	align-items: center;
}

.settings-icon {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	background: rgba(0, 122, 255, 0.1);
}

.settings-icon .icon {
	font-size: 32rpx;
	color: #007AFF;
}

.empty-state {
	text-align: center;
	padding: 100rpx 0;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
	display: block;
	margin-bottom: 30rpx;
}

.add-btn {
	background: #007AFF;
	color: white;
	padding: 20rpx 40rpx;
	border-radius: 10rpx;
	border: none;
	font-size: 28rpx;
}

.fab {
	position: fixed;
	bottom: 40rpx;
	right: 40rpx;
	width: 100rpx;
	height: 100rpx;
	background: #007AFF;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 20rpx rgba(0,122,255,0.3);
}

.fab-icon {
	color: white;
	font-size: 40rpx;
	font-weight: bold;
}
</style>